import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QTreeWidget, QTreeWidgetItem, QLabel, QSplitter, QToolBar,
    QStatusBar, QProgressBar, QMessageBox, QHeaderView
)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import QUrl, Qt
from PyQt6.QtGui import QIcon, QFont, QAction, QBrush, QColor




class WebBrowser(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt6 网页浏览器")
        self.resize(1400, 900)

        # 创建主部件和布局
        main_widget = QWidget()
        main_layout = QHBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # 创建分割器
        splitter = QSplitter()
        splitter.setChildrenCollapsible(False)

        # 创建左侧导航面板
        self.nav_panel = self.create_navigation_tree()
        splitter.addWidget(self.nav_panel)

        # 创建右侧网页视图
        self.web_view = QWebEngineView()
        self.web_view.load(QUrl("https://app.powerbi.com/"))
        splitter.addWidget(self.web_view)

        # 设置分割器初始比例
        splitter.setSizes([250, 1150])

        main_layout.addWidget(splitter)
        self.setCentralWidget(main_widget)

        # 创建工具栏
        self.create_toolbar()

        # 创建状态栏
        self.create_statusbar()

        # 连接信号
        self.web_view.loadStarted.connect(self.page_loading_started)
        self.web_view.loadProgress.connect(self.page_loading_progress)
        self.web_view.loadFinished.connect(self.page_loading_finished)
        # 移除了 urlChanged.connect(self.url_changed) 连接

        # 设置样式
        self.apply_styles()

    def create_navigation_tree(self):
        """创建左侧树形导航面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # 标题
        title = QLabel("网站导航")
        title.setFont(QFont("微软雅黑", 12, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title)

        # 创建树形控件
        self.tree = QTreeWidget()
        self.tree.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.tree.setHeaderHidden(True)
        self.tree.setIndentation(15)

        # 设置列数
        self.tree.setColumnCount(1)

        # 添加网站分类和项目
        self.populate_tree()

        # 默认展开所有节点
        self.tree.expandAll()

        # 连接点击事件
        self.tree.itemClicked.connect(self.tree_item_clicked)

        layout.addWidget(self.tree)

        return panel

    def populate_tree(self):
        """填充树形控件数据"""
        # 定义网站分类结构
        categories = {
            "Power BI": {
                "icon": "📊",
                "sites": [
                    {"name": "Power BI 服务", "url": "https://app.powerbi.com/", "icon": "🏠"},
                    {"name": "Power BI 文档", "url": "https://docs.microsoft.com/power-bi/", "icon": "📖"},
                    {"name": "Power BI 社区", "url": "https://community.powerbi.com/", "icon": "👥"},
                    {"name": "Power BI 创意", "url": "https://ideas.powerbi.com/", "icon": "💡"},
                    {"name": "报表服务器", "url": "https://powerbi.microsoft.com/report-server/", "icon": "📈"},
                ]
            },
            "搜索引擎": {
                "icon": "🔍",
                "sites": [
                    {"name": "百度", "url": "https://www.baidu.com", "icon": "B"},
                    {"name": "谷歌", "url": "https://www.google.com", "icon": "G"},
                ]
            },

            "数据分析": {
                "icon": "📈",
                "sites": [
                    {"name": "Kaggle", "url": "https://www.kaggle.com", "icon": "🏆"},
                    {"name": "Tableau Public", "url": "https://public.tableau.com", "icon": "📊"},
                ]
            },
            "视频平台": {
                "icon": "📺",
                "sites": [
                    {"name": "哔哩哔哩", "url": "https://www.bilibili.com", "icon": "B"},

                ]
            },
            "购物平台": {
                "icon": "🛒",
                "sites": [
                    {"name": "淘宝", "url": "https://www.taobao.com", "icon": "T"},

                ]
            }
        }

        # 添加分类节点
        for category, data in categories.items():
            # 创建分类节点
            category_item = QTreeWidgetItem(self.tree)
            category_item.setText(0, f"{data['icon']} {category}")
            category_item.setData(0, Qt.ItemDataRole.UserRole, None)  # 分类节点没有URL
            category_item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)

            # 添加分类下的网站
            for site in data["sites"]:
                site_item = QTreeWidgetItem(category_item)
                site_item.setText(0, f"{site['icon']} {site['name']}")
                site_item.setData(0, Qt.ItemDataRole.UserRole, site["url"])
                site_item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)

        # 调整列宽
        self.tree.header().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)

    def create_toolbar(self):
        """创建工具栏"""
        toolbar = QToolBar("导航工具栏")
        toolbar.setMovable(False)
        self.addToolBar(toolbar)

        # 后退按钮
        back_action = QAction(QIcon(":back"), "后退", self)
        back_action.triggered.connect(self.web_view.back)
        toolbar.addAction(back_action)

        # 前进按钮
        forward_action = QAction(QIcon(":forward"), "前进", self)
        forward_action.triggered.connect(self.web_view.forward)
        toolbar.addAction(forward_action)

        # 刷新按钮
        refresh_action = QAction(QIcon(":refresh"), "刷新", self)
        refresh_action.triggered.connect(self.web_view.reload)
        toolbar.addAction(refresh_action)

        toolbar.addSeparator()

        # 主页按钮
        home_action = QAction(QIcon(":home"), "主页", self)
        home_action.triggered.connect(self.go_home)
        toolbar.addAction(home_action)

        # 添加书签按钮
        bookmark_action = QAction(QIcon(":bookmark"), "添加书签", self)
        bookmark_action.triggered.connect(self.add_bookmark)
        toolbar.addAction(bookmark_action)

    def create_statusbar(self):
        """创建状态栏"""
        status_bar = QStatusBar()
        self.setStatusBar(status_bar)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximumWidth(200)
        self.progress_bar.setVisible(False)
        status_bar.addPermanentWidget(self.progress_bar)

        # 状态标签
        self.status_label = QLabel("就绪")
        status_bar.addWidget(self.status_label)

    def tree_item_clicked(self, item, column):
        """树形控件项点击事件处理"""
        url = item.data(0, Qt.ItemDataRole.UserRole)
        if url:
            self.web_view.load(QUrl(url))
            self.status_label.setText(f"正在加载: {item.text(0)}")

    def go_home(self):
        """导航到主页（Power BI）"""
        self.web_view.load(QUrl("https://app.powerbi.com/"))
        self.status_label.setText("正在加载主页: Power BI 服务")

    def add_bookmark(self):
        """添加当前页面到书签"""
        current_url = self.web_view.url().toString()
        current_title = self.web_view.title()

        if not current_url or current_url == "about:blank":
            QMessageBox.warning(self, "添加书签", "当前页面无法添加为书签")
            return

        # 查找或创建"我的书签"分类
        bookmark_category = None
        for i in range(self.tree.topLevelItemCount()):
            item = self.tree.topLevelItem(i)
            if item.text(0) == "📌 我的书签":
                bookmark_category = item
                break

        if not bookmark_category:
            bookmark_category = QTreeWidgetItem(self.tree)
            bookmark_category.setText(0, "📌 我的书签")
            bookmark_category.setData(0, Qt.ItemDataRole.UserRole, None)
            bookmark_category.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
            self.tree.insertTopLevelItem(0, bookmark_category)
            bookmark_category.setExpanded(True)

        # 创建书签项
        bookmark_item = QTreeWidgetItem(bookmark_category)
        bookmark_item.setText(0, f"🔖 {current_title[:30]}")
        bookmark_item.setData(0, Qt.ItemDataRole.UserRole, current_url)
        bookmark_item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)

        # 展开书签分类
        bookmark_category.setExpanded(True)

        # 提示用户
        QMessageBox.information(self, "添加书签", f"已添加书签: {current_title[:50]}")

    def page_loading_started(self):
        """页面开始加载时的处理"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.status_label.setText("正在加载页面...")

    def page_loading_progress(self, progress):
        """页面加载进度更新时的处理"""
        self.progress_bar.setValue(progress)

    def page_loading_finished(self, success):
        """页面加载完成时的处理"""
        self.progress_bar.setVisible(False)
        if success:
            self.status_label.setText("页面加载完成")
        else:
            self.status_label.setText("页面加载失败")
            QMessageBox.warning(self, "加载失败", "网页加载失败，请检查网络连接或URL是否正确")

    # 移除了 url_changed 方法

    def apply_styles(self):
        """应用样式表"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f5;
            }
            QTreeWidget {
                background-color: #ffffff;
                border: none;
                font-size: 14px;
                outline: 0;
            }
            QTreeWidget::item {
                padding: 8px 12px;
                border-bottom: 1px solid #e8e8e8;
            }
            QTreeWidget::item:selected {
                background-color: #e6f7ff;
                color: #1890ff;
                border-left: 3px solid #1890ff;
            }
            QLabel {
                padding: 12px;
                font-weight: bold;
                background-color: #fafafa;
                border-bottom: 1px solid #e8e8e8;
            }
            QToolBar {
                background-color: #f0f0f0;
                border-bottom: 1px solid #d0d0d0;
                spacing: 5px;
                padding: 5px;
            }
            QLineEdit {
                padding: 6px;
                border: 1px solid #d0d0d0;
                border-radius: 3px;
                min-width: 300px;
            }
            QProgressBar {
                border: 1px solid #d0d0d0;
                border-radius: 3px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #1890ff;
                width: 10px;
            }
            QStatusBar {
                background-color: #f0f0f0;
                border-top: 1px solid #d0d0d0;
                font-size: 12px;
            }
        """)

        # 设置树形控件中分类节点的样式
        for i in range(self.tree.topLevelItemCount()):
            item = self.tree.topLevelItem(i)
            item.setBackground(0, QBrush(QColor(245, 245, 245)))
            item.setFont(0, QFont("微软雅黑", 10, QFont.Weight.Bold))


if __name__ == '__main__':
    app = QApplication(sys.argv)

    # 设置应用样式
    app.setStyle("Fusion")

    browser = WebBrowser()
    browser.show()
    sys.exit(app.exec())
